import * as types from './mutation-types'
import Vue from 'vue'
import { m7Language, getCallLabelKeys } from '@/utils/m7Utils.js'
import m7dicMap from '@utils/m7dicMap'
let beforeMasking = {time: 0}
export default {
  [types.SET_TRANSFER_NOTICE](state, data) {
    Vue.set(state, 'transferNotice', data)
  },
  [types.SET_TRANSFER_NO_CONFIRM_NOTICE](state, data) {
    Vue.set(state, 'transferNoConfirmNotice', data)
  },
  [types.SET_EXPORTLIST] (state, data) {
    state.globalExport.list.push(data)
    if (!state.globalExport.show) {
      state.globalExport.show = true
    }
  },
  [types.ALL_KEY_LANELS] (state, data) {
    state.allKeyLabels = getCallLabelKeys(data || [], {})
  },
  [types.DEL_EXPORTLIST] (state, data) {
    if (state.globalExport.list.length > 0) {
      for (let i = state.globalExport.list.length - 1; i >= 0; i--) {
        if (data.id === state.globalExport.list[i].id) {
          state.globalExport.list.splice(i, 1)
        }
      }
    }
    if (state.globalExport.list.length !== 0) {
      state.globalExport.show = true
    } else {
      state.globalExport.show = false
    }
    console.log(state.globalExport.list)
  },
  [types.NOTICEBUSSINESS] (state, data) {
    state.noticeBusJump = data
  },
  [types.NOTICENEW] (state, data) {
    state.noticeWenJump = data
  },
  [types.NOTICECUSTOMER] (state, data) {
    state.noticeCustJump = data
  },
  [types.BLANK] (state, data) {
    state.blank = data
  },
  [types.SET_DICVERSION] (state, data) {
    state.dicVersion = data
  },
  [types.SET_QRCODE_TOKEN] (state, {token}) {
    state.mobileCheckToken = token
  },
  [types.SET_BIGIMG] (state, data) {
    state.bigImg.imgUrl = data.url
    state.bigImg.imgShow = data.show
    state.bigImg.index = data.index || 0
    state.bigImg.list = data.list || []
  },
  [types.SET_OLD_BIGIMG] (state, data) {
    state.bigOldImg.imgUrl = data.url
    state.bigOldImg.imgShow = data.show
  },
  [types.SET_AUDIO_VUDIO] (state, data) {
    state.massMedia.textUrl = data.url
    state.massMedia.textShow = data.show
    state.massMedia.flag = data.flag
  },
  [types.CHANGSTATUS] (state, data) {
    state.isHomePage = data
  },
  [types.IS_CALL_INTERFACE] (state, data) {
    state.isCallInterface = data
  },
  [types.IS_CALL_OUT_INTERFACE] (state, data) {
    state.isCallOutInterface = data
  },
  [types.IS_CALL_INTERFACEBUTTON] (state, data) {
    state.isCallInterfaceButton = data
  },
  [types.IS_CALL_OUT_INTERFACEBUTTON] (state, data) {
    state.isCallOutInterfaceButton = data
  },
  [types.SET_CUR_CALL_SHEETID] (state, data) {
    state.curCallSheetId = data
  },
  /**
   * types.SET_ERROR
   * types.SET_SUCCESS
   * 处理必要返回的响应的message
   * types.SET_EXIT
   * 同账号在不同地方登陆将用户强制退出登录
   */
  [types.SET_ERROR] (state, err) {
    state.error = err
  },
  [types.SET_EXIT] (state, exit) {
    state.exit = exit
  },
  [types.UNBINDGATEWAY] (state, data) {
    state.unBindGateway = data
  },
  [types.SET_SUCCESS] (state, success) {
    state.success = success
  },
  [types.SET_INFO] (state, info) {
    state.info = info
  },
  // end
  [types.SET_CURRENT_CUSTOMER] (state, { data, type, tabType, businessId }) {
    if (tabType === 'cdr_call') {
      Vue.set(state[type].current[tabType], 'currentCustomer', data)
      // Vue.set(state[type].current[tabType][businessId], 'currentCustomer', data)
    } else if (tabType === 'webchat_todo') {
      Vue.set(state[type].current[tabType], 'currentCustomer', data)
      Vue.set(state[type].current[tabType].currentSession[businessId], 'currentCustomer', data)
    } else if (type === 'business') {
      Vue.set(state[type].current, 'currentCustomer', data)
    } else {
      Vue.set(state[type].current[tabType], 'currentCustomer', data)
    }
  },
  [types.UPDATE_CUSTOMER_INFO] (state, { data }) {
    // 更新通话模块客户信息
    for (let callTab in state.call.current) {
      if (data) {
        if (callTab === 'cdr_call') {
          for (let sessionId in state.call.current.cdr_call.currentSession) {
            let currentCustomer = state.call.current.cdr_call.currentSession[sessionId]
            if (currentCustomer && currentCustomer._id === data._id) {
              Object.assign(currentCustomer, data)
            }
          }
        } else {
          if (state.call.current[callTab].currentCustomer && state.call.current[callTab].currentCustomer._id === data._id) {
            Object.assign(state.call.current[callTab].currentCustomer, data)
          }
        }
      }
    }

    // 更新通话模块列表客户名称
    for (let callTab in state.call.callList) {
      state.call.callList[callTab].list && state.call.callList[callTab].list.forEach(callInfo => {
        if (data) {
          if (callInfo.CUSTOMER_ID === data._id) {
            if (data.name) {
              callInfo.CUSTOMER_NAME = data.name
            }
            if (data.status) {
              callInfo.CUSTOMER_STATUS = data.status
            }
          }
        }
      })
      if (callTab === 'cdr_call') {
        let storage = window.sessionStorage
        if (storage.getItem('callList')) { // 来电里面切换客户头像或者是更改客户名字时，更改session里面的值
          storage.setItem('callList', JSON.stringify(state.call.callList[callTab].list))
        }
      }
    }

    // 更新在线咨询模块客户信息
    for (let webchatTab in state.webchat.current) {
      if (webchatTab === 'webchat_todo') {
        for (let sessionId in state.webchat.current.webchat_todo.currentSession) {
          let currentCustomer = state.webchat.current.webchat_todo.currentSession[sessionId].currentCustomer
          if (currentCustomer && currentCustomer._id === data._id) {
            Object.assign(currentCustomer, data)
          }
        }
      } else {
        if (state.webchat.current[webchatTab].currentCustomer && state.webchat.current[webchatTab].currentCustomer._id === data._id) {
          Object.assign(state.webchat.current[webchatTab].currentCustomer, data)
        }
      }
    }

    // 更新在线咨询模块列表客户名称
    for (let webchatTab in state.webchat.webchatList) {
      state.webchat.webchatList[webchatTab].list && state.webchat.webchatList[webchatTab].list.forEach(webchatInfo => {
        if (webchatInfo.custId === data._id) {
          if (data.name) {
            webchatInfo.sName = data.name
          }
          if (data.status) {
            webchatInfo.cust_status = data.status
          }
        }
      })
    }

    // 更新邮件模块客户信息
    for (let emailTab in state.email.current) {
      if (state.email.current[emailTab].currentCustomer && state.email.current[emailTab].currentCustomer._id === data._id) {
        Object.assign(state.email.current[emailTab].currentCustomer, data)
      }
    }

    // 更新邮件模块列表客户名称
    for (let emailTab in state.email.emailList) {
      state.email.emailList[emailTab].list && state.email.emailList[emailTab].list.forEach(emailInfo => {
        if (emailInfo.customerId === data._id) {
          if (data.name) {
            emailInfo.custName = data.name
          }
          if (data.status) {
            emailInfo.cust_status = data.status
          }
        }
      })
    }
    // 更新客户模块客户信息
    for (let customerTab in state.customer.current) {
      if (state.customer.current[customerTab].currentCustomer && state.customer.current[customerTab].currentCustomer._id === data._id) {
        state.customer.current[customerTab].currentCustomer = Object.assign({}, state.customer.current[customerTab].currentCustomer, data)
        // Object.assign(state.customer.current[customerTab].currentCustomer, data)
      }
    }

    // 更新客户模块列表客户信息
    for (let customerTab in state.customer.customerList) {
      state.customer.customerList[customerTab].list && state.customer.customerList[customerTab].list.forEach((customer, index) => {
        if (customer._id === data._id) {
          if (customerTab === 'customer_my' && data.owner && customer.owner !== data.owner || customerTab === 'customer_plan' && data.owner && customer.owner !== data.owner) {
            Vue.set(state.customer.transCache, 'refreshLeft', Math.random())
          } else {
            Object.assign(customer, data)
            // state.customer.customerList[customerTab].list[index] = Object.assign({}, customer, data)
          }
        }
      })
    }

    // 更新工单模块客户信息
    if (state.business.current.currentCustomer && state.business.current.currentCustomer._id === data._id) {
      Object.assign(state.business.current.currentCustomer, data)
    }

    // 更新工单模块列表客户名称
    state.business.businessList.list && state.business.businessList.list.forEach(businessInfo => {
      if (businessInfo.customer === data._id) {
        if (data.name) {
          businessInfo.name = data.name
        }
        if (data.status) {
          businessInfo.cust_status = data.status
        }
      }
    })

    // 更新来电弹屏模块客户信息
    if (state.cti.currentCustInfo && state.cti.currentCustInfo._id === data._id) {
      Object.assign(state.cti.currentCustInfo, data)
    }
  },
  // [types.XLSXEXPORTMODE] (state, data) {
  //   state.xlsxExportMode = data
  // },
  [types.IFRAMENOTIFY] (state, data) {
    state.iframeNotify = data
  },
  [types.UPDATENOTIFYFLAG] (state, data) {
    state.iframeNotify.notifyFlag = data
  },
  [types.UPDATEDATEVER] (state, data) {
    state.iframeNotify.updateVer.updateVer = data
  },
  [types.IFRAMEMESSAGE] (state, data) {
    Vue.set(state, 'iframeMessage', data)
  },
  [types.UPDATELANG] (state, data) {
    state.lang = data
  },
  [types.INIT_CONFIG] (state, { data }) {
    state.attachmentMaxSize = data.attachmentMaxSize || '50mb'
    state.pushServerUrl = data.ccPushUrl
    state.serverDiffTime = data.serverDiffTime
    state.privatization = data.privatization
    state.isOem = data.isOem || false
    state.dateLimit = data.reportBeginTime ? data.reportBeginTime.year || '2020' : '2020'
    state.isCaptcha = data.isCaptcha || false
    state.captchaId = data.captchaId || ''
    state.isRealTimeExport = data.isRealTimeExport || false
    // 处理腾讯云或是阿里云的url地址
    state.platform_urls = data.platform_urls || {}
    if (data.newSkillUrl) {
      state.newSkill = data.newSkillUrl
    }
    if (data.newSkillImg) {
      state.newSkillImg = data.newSkillImg
    }
    if (data.adUrl) {
      state.aiExtension = data.adUrl
    }
    if (data.adShow) {
      state.aiExtensionShow = data.adShow
    }
    let loginBody = document.getElementById('login-body')
    let shortcut = document.getElementById('shortcut')
    if (data.oemFlag) {
      state.oemObj.oemFlag = data.oemFlag
      state.oemObj.oemInfo = data.oemInfo || {}
    } else {
      loginBody.className = 'login-loading'
      shortcut.setAttribute('href', '/img/logo.ico')
    }
  },
  [types.UPDATE_PUSH_URL] (state, result) {
    state.pushServerUrl = result.data ? result.data.server : ''
  },
  [types.SET_KICK_FLAG] (state, kickOut) {
    state.kickOut = kickOut
  },
  [types.SET_LABEL_POSITION] (state, position) {
    state.labelPosition = position
  },
  [types.SIGNIN] (state, {data}) {
    Vue.set(state, 'login', data.success)
    if (data.account) {
      if (!data.account.pbx) {
        data.account.pbx = []
      }
    }
    Vue.set(state, 'session', data)
    // 是否是渠道隐藏7moor关键字
    if (data.account.proxyType && data.account.proxyType === 'channel') {
      state.oemObj.oemFlag = true
    }
  },
  [types.SIGNINBYTOKEN] (state, {data}) {
    Vue.set(state, 'login', data.success)
    Vue.set(state, 'session', data)
    if (data.extenType === 'null') {
      state.phoneBarShow = false
    }
    // 是否是渠道隐藏7moor关键字
    if (data.account.proxyType && data.account.proxyType === 'channel') {
      state.oemObj.oemFlag = true
    }
  },
  // [types.SINGIN1] (state, {data}) {
  //   Vue.set(state, 'bloon', data)
  // },
  [types.SIGNOUT] (commit) {

  },
  [types.MASKING] (state, data) {
    let currentTime = new Date().getTime()
    if (beforeMasking.show === false && data.show === true) {
      if (currentTime - beforeMasking.time < 500) {
        data.show = false
      }
    }
    beforeMasking.show = data.show
    beforeMasking.time = currentTime
    state.masking = data
  },
  // 以防dicMap还不存在的时候已经去请求了其它的cache
  [types.SET_DICMAP] (state, {dicMap}) {
    // if (state.session.dicMap) {
    //   Object.assign(state.session.dicMap, dicMap)
    // } else {
    //   state.session.dicMap = dicMap
    // }
    // 初始化工单缓存
    dicMap.busCache = {}
    m7dicMap.setAll(dicMap)
  },
  [types.SET_IVRMAP] (state, {ivrMap, PBX}) {
    let obj = {}
    obj[PBX] = ivrMap
    if (state.session.ivrMap) {
      Object.assign(state.session.ivrMap, obj)
    } else {
      state.session.ivrMap = obj
    }
  },
  [types.SET_THIRDAPP] (state, data) {
    state.thirdApp = data
  },
  [types.EMPTY_IVRMAP] (state) {
    state.session.ivrMap = {}
  },
  [types.IS_GET_ALL_IVRMAP] (state) {
    state.session.isGetAllIvrMap = true
  },
  [types.SET_ASSIGN_IVRMAP] (state, {type, assign, PBX}) {
    try {
      let obj = {}
      obj = assign
      if (!state.session.ivrMap) {
        Vue.set(state.session, 'ivrMap', {})
      }
      if (PBX && !state.session.ivrMap[PBX]) {
        Vue.set(state.session.ivrMap, PBX, {})
      }
      if (state.session.ivrMap[PBX] && !state.session.ivrMap[PBX].data) {
        Vue.set(state.session.ivrMap[PBX], 'data', {})
      }
      if (type === 'allBlackList' || type === 'allFlows' || type === 'allPhoneBarConfig') {
        if (state.session.ivrMap[PBX] && state.session.ivrMap[PBX][type]) {
          Object.assign(state.session.ivrMap[PBX][type], obj)
        } else {
          console.log(obj, PBX, type)
          Vue.set(state.session.ivrMap[PBX], type, obj)
        }
      } else {
        if (state.session.ivrMap[PBX] && state.session.ivrMap[PBX][type]) {
          Object.assign(state.session.ivrMap[PBX].data[type], obj)
        } else {
          console.log(obj, PBX, type)
          Vue.set(state.session.ivrMap[PBX].data, type, obj)
        }
      }
    } catch (e) {
      console.log(e)
    }
  },
  [types.SET_SKILL_GROUP_LOADING] (state, data) {
    state.config.channelConfig.call.skillGroupLoading = data
  },
  [types.SET_IVRMAP_DETAIL] (state, {PBX, typeName, data, flag, node}) { // flag 是否要插到data对象里面
    if (state.session.ivrMap && state.session.ivrMap[PBX]) {
      // let ivrMap = state.session.ivrMap[PBX]
      if (flag === 'data') {
        // ivrMap.data[typeName] = data
        Vue.set(state.session.ivrMap[PBX].data, typeName, data)
      } else {
        // ivrMap[typeName] = data
        Vue.set(state.session.ivrMap[PBX], typeName, data)
      }
    } else { // vuex中找不到，即发送请求
      let actionData = {Account: state.session.account.account, PBX: PBX}
      node.$store.dispatch('getAllNodesByPbxForSkill', actionData)
    }
  },
  [types.PUSH_TYPE_DICDATA] (state, {type, data}) {
    // let dicMap = state.session.dicMap
    // Vue.set(state.session.dicMap, type, dicMap[type])
    m7dicMap.addOneCache(type, data)
  },
  [types.SET_TYPE_DICDATA] (state, {type, data}) {
    // if (!state.session.dicMap) {
    //   Vue.set(state.session, 'dicMap', {})
    // }
    // Vue.set(state.session.dicMap, type, data)
    m7dicMap.updateCache(type, data)
  },
  [types.SET_OPTIONS_DICMAP] (state, options) {
    // if (!state.session.dicMap) {
    //   Vue.set(state.session, 'dicMap', {})
    // }
    // Vue.set(state.session.dicMap, 'options', options)
    m7dicMap.updateCache('options', options)
  },
  [types.SET_NOVICE_KEY_DICMAP] (state, data) {
    // if (!state.session.dicMap) {
    //   Vue.set(state.session, 'dicMap', {})
    // }
    // let noviceObj = state.session.dicMap.guidance || {}
    let noviceObj = m7dicMap.getCache('guidance') || {}
    for (let i in noviceObj) {
      if (i === data.key) {
        noviceObj[i] = data.status
        break
      }
    }
    // Vue.set(state.session.dicMap, 'guidance', noviceObj)
    m7dicMap.updateCache('guidance', noviceObj)
  },
  [types.SET_MENU] (state, {data}) {
    Vue.set(state.session, 'clientMenu', data)
  },
  [types.USER_TOKEN] (state, {data}) {
    Vue.set(state.session.user, 'userToken', data)
  },
  [types.USER_EDIT] (state, data) {
    if (data) {
      let agents = m7dicMap.getCache('agents')
      let agentItem = agents.filter(obj => obj._id === data._id)[0]
      if (agentItem) {
        agentItem.im_icon = data.im_icon
      }
      for (let key in data) {
        if (data[key]) {
          Vue.set(state.session.user, key, data[key])
          // state.session.user[key] = data[key]
        }
      }
    }
    if (data.password) {
      let user = JSON.parse(window.sessionStorage.getItem('loginData'))
      user.password = data.password
      let form = JSON.parse(JSON.stringify(user))
      delete form.lastCodeKey
      delete form.authCode
      window.sessionStorage.setItem('loginData', JSON.stringify(form))
    }
  },
  [types.LOGINED] (state, data) {
    Vue.set(state.session, 'logined', data)
    Vue.set(state, 'login', data)
  },
  [types.SET_FILEDOWNLOAD] (state, data) {
    state.fileDown = data
  },
  [types.SET_NOTIFY] (state, data) {
    state.notify = data
  },
  [types.IVR_SOUND_TRANSFER] (state, data) {
    state.ivrSoundTransfer = data
  },
  [types.SET_DRAGPOP] (state, data) {
    if (data === 'close') {
      state.dragPop.open = false
    } else {
      state.dragPop = data
    }
  },
  [types.SET_IMAGES] (state, {id, headUrl}) {
    state.webchat.current.webchat_todo.chatInfoById[id].headUrl = headUrl
  },
  [types.SER_HEADER_IMG] (state, data) {
    state.webchat.current.webchat_todo.currentSession[data.sessionId].sName = data.data.sName
  },
  [types.CHANGE_STATE_INVITECON] (state, data) {
    let flag = true
    let index = -2
    if (state.inviteContents.length) {
      for (let i = 0; i < state.inviteContents.length; i++) {
        if (state.inviteContents[i].sessionId === data.sessionId) {
          flag = false
          index = i
        }
      }
    }
    // 增加在线咨询邀请的list
    if (data.todo === 'add' && flag) {
      state.inviteContents.push(data)
    }
    // 删除在线咨询邀请的listuser-pic
    if (data.todo === 'delete' && !flag) {
      state.inviteContents.splice(index, 1)
    }
    Vue.set(state, 'inviteContents', state.inviteContents)
    // 改变在线咨询邀请的list的展示
    if (state.inviteContents.length) {
      Vue.set(state, 'inviteCon', true)
    } else {
      Vue.set(state, 'inviteCon', false)
    }
  },
  // 关闭高级搜索
  [types.CLOSE_ADV_SEARCH] (state, data) {
    Vue.set(state, 'closeAdvSearch', Math.random())
  },
  [types.CHANGE_PASSWORD_ADVICE] (state) {
    let newDate = new Date()
    let time = newDate.getTime()
    let lastUpdate = state.session.user.passwordLastUpdate
    let differ = Math.floor((time - lastUpdate) / 1000 / 60 / 60 / 24)
    differ > 90 && Vue.set(state, 'isPopup', state.login)
  },
  // 质检 往session添加任务模板
  [types.PUSH_TASK_TEM] (state, data) {
    let qualityTasks = m7dicMap.getCache('qualityTasks') || []
    qualityTasks.push(data)
    m7dicMap.updateCache('qualityTasks', qualityTasks)
  },
  // 质检 往session添加条件模板
  [types.PUSH_CONDITION_TEM] (state, data) {
    // state.session.dicMap.qualityConditionTemplates.unshift(data)
    let qualityConditionTemplates = m7dicMap.getCache('qualityConditionTemplates')
    qualityConditionTemplates.unshift(data)
    m7dicMap.updateCache('qualityConditionTemplates', qualityConditionTemplates)
  },
  /**
   * 动态添加  来电 与 在线咨询待处理组件
   */
  [types.ADD_ROUTES] (state, data) {
    state.routes[data.type] = Object.assign({}, state.routes[data.type], {
      [data.name]: {
        cid: data.cid,
        component: data.component
      }
    })
  },
  // ADD by liangqi
  [types.REMOVE_ROUTE] (state, data) {
    if (state.routes[data.type]) {
      Vue.delete(state.routes[data.type], data.id)
    }
  },
  // ADD end

  [types.CHANGE_SESSION_ACOUNT] (state, data) {
    for (let key in data) {
      window.localStorage.setItem(key, data[key])
      // state.session.account[key] = data[key]
      Vue.set(state.session.account, key, data[key])
    }
  },
  [types.SET_BING_CALL_PROCESS] (state, data) {
    if (data === 'close') {
      state.bigCallProcess.open = false
    } else {
      state.bigCallProcess = data
    }
  },
  [types.IS_NORMAL_CALL_CONFIG] (state, data) {
    state.isNormalCallConfig = data
  },
  [types.SET_CTI_UI_DESC] (state, data) {
    let obj = {
      unregister: m7Language('cti.unlink'),
      peerstate: m7Language('cti.free'),
      dialing: m7Language('cti.dialing'),
      innerDialing: m7Language('cti.dialing'),
      belling: m7Language('cti.belling'),
      innerBelling: m7Language('cti.belling'),
      listening: m7Language('cti.listening'),
      talking: m7Language('cti.talking'),
      threeWayTalking: m7Language('cti.threeWayTalking'),
      innerTalking: m7Language('cti.innerTalking'),
      dialTalking: m7Language('cti.dialTalking'),
      listened: m7Language('cti.listened'),
      hold: m7Language('cti.hold'),
      consultTalking: m7Language('cti.talking'),
      dialTransfer: m7Language('cti.dialTransfer'),
      transfer: m7Language('cti.transferCall'),
      offline: m7Language('cti.offline'),
      ready: m7Language('cti.ready'),
      transferBelling: m7Language('cti.transferBelling'),
      transferDialing: m7Language('cti.transferBelling')
    }
    state.cti.globalLet._cti_ui_desc = {...obj}
  },
  [types.navMenuState] (state) {
    state.navMenuState = !state.navMenuState
    window.sessionStorage.setItem('navMenuState', JSON.stringify(state.navMenuState))
  },
  [types.getNavMenuState] (state) {
    state.navMenuState = JSON.parse(window.sessionStorage.getItem('navMenuState'))
  },
  [types.updatedicMapGetterVersion] (state) {
    state.session.dicMapGetterVersion++
  },
  // 修改远程控制参数
  [types.updateRemoteControlInfo] (state, data) {
    state.RemoteControl.isRemoteControl = data.isRemoteControl
    state.RemoteControl.remoteFrom = data.remoteFrom
    state.RemoteControl.remoteCustSid = data.remoteCustSid
    state.RemoteControl.customerSource = data.customerSource
  },
  [types.SET_VERIFY_SHOW] (state, data) {
    state.verifyShow = data
  },
  [types.SET_REMOTE_AGENTS] (state, data) {
    Vue.set(state.session.account, 'exten_visible', data)
  },
  [types.IS_NEW_CARD_STYLE] (state, styleObj) {
    Vue.set(state.isNewCardStyle, styleObj.type, styleObj.data)
  },
  [types.FileDOMAIN] (state, data) {
    state.fileDomain = data
  },
  [types.IS_USE_QINIU] (state, data) {
    state.isUseQiniu = data
    // state.isUseQiniu = true
  }
}

